package cn.pconline.officialclub.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.CensorIntroduceService;
import cn.pconline.autoclub.service.CensorNoticeService;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.Result;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.entity.OClubFocusImg;
import cn.pconline.officialclub.entity.OClubNotice;
import cn.pconline.officialclub.entity.OCommonMember;
import cn.pconline.officialclub.service.CensorOClubNoticeService;
import cn.pconline.officialclub.service.OClubService;

import java.util.ArrayList;
import java.util.Date;

/**
 *
 * @author ppc
 */
@Controller
@RequestMapping(value = "/brand/club")
public class OClubController extends WebKit {

    @Autowired
    private OClubService oClubService;
    @Autowired
    private CensorNoticeService censorNoticeService;
    @Autowired
    private CensorIntroduceService censorIntroduceService;
    @Autowired
    private CensorOClubNoticeService censorOClubNoticeService;
    final static String defaultImg = "http://img0.pcauto.com.cn/pcauto/1501/23/5840763_280x140.jpg";

    /**
     * 车友会首页（不需要登录）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index(HttpServletRequest request, HttpServletResponse resp) {
        long oClubId = WebUtils.paramOClubId(request);
        OClub club = oClubService.findValidClub(oClubId);
        if (club == null) {
            return redirect404(resp);
        }
        User user = userAuth.getUser(request, resp);
        OCommonMember member = null;
        if (user.getUid() > 0) {
            member = oMemberService.findCommonMember(user.getUid(), oClubId);
        }
        boolean isClubAdmin = false;
        boolean isPresident = false;
        if (member != null) {
            isClubAdmin = member.isAdmin();
            isPresident = member.getAdminType() == OCommonMember.ADMIN_TYPE_PRESIDENT;
        }
        request.setAttribute("user", user);
        request.setAttribute("isUserLock", oMemberService.isUserLock(user, oClubId));
        request.setAttribute("oClub", club);
        request.setAttribute("pageNo", 1);
        request.setAttribute("isIndex", true);
        request.setAttribute("isMember", member != null);
        request.setAttribute("isLogin", user.getUid() > 0);
        request.setAttribute("isPresident", isPresident);
        request.setAttribute("isClubAdmin", isClubAdmin);
        return getPcTemplPath("/club/index");
    }

    @RequestMapping(value = "/logo.do", method = RequestMethod.GET)
    public String logo(HttpServletRequest request, HttpServletResponse resp) {
        long oClubId = WebUtils.paramOClubId(request);
        OClub club = oClubService.findValidClub(oClubId);
        if (club == null) {
            return redirect404(resp);
        }
        if (!isAdmin(request, resp)) {
            return null;
        }
        request.setAttribute("oClub", club);
        return getPcTemplPath("/club/logo");
    }

    @RequestMapping(value = "/saveLogo.do", method = RequestMethod.POST)
    public void saveLogo(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long oClubId = WebUtils.paramOClubId(req);
        String logoUrl = WebUtils.param(req, "logo", "");
        if (oClubId > 0) {
            OClub oclub = oClubService.findValidClub(oClubId);
            if (oclub == null) {
                printMsg(resp, Result.dataError("oClubId错误"));
                return;
            }
            if (!isAdmin(req, resp)) {
                return;
            }
            User user = userAuth.getUser(req, resp);
            oclub.setLogo(logoUrl);
            oclub.setUpdateBy(user.getUid());
            oClubService.updateLogo(oclub);
            printMsg(resp, Result.success("保存成功"));
        } else {
            printMsg(resp, Result.dataError("oClubId错误"));
        }
    }

    @RequestMapping(value = "/coverImage.do", method = RequestMethod.GET)
    public String coverImage(HttpServletRequest request, HttpServletResponse resp) {
        long oClubId = WebUtils.paramOClubId(request);
        OClub club = oClubService.findValidClub(oClubId);
        if (club == null) {
            return redirect404(resp);
        }
        if (!isAdmin(request, resp)) {
            return null;
        }
        request.setAttribute("oClub", club);
        return getPcTemplPath("/club/coverImage");
    }

    @RequestMapping(value = "/saveCoverImage.do", method = RequestMethod.POST)
    public void saveCoverImage(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long oClubId = WebUtils.paramOClubId(req);
        String coverImage = WebUtils.param(req, "coverImage", "");
        if (oClubId > 0) {
            OClub oclub = oClubService.findValidClub(oClubId);
            if (oclub == null) {
                printMsg(resp, Result.dataError("oClubId错误"));
                return;
            }
            if (!isAdmin(req, resp)) {
                return;
            }
            User user = userAuth.getUser(req, resp);
            oclub.setCoverImage(coverImage);
            oclub.setUpdateBy(user.getUid());
            oClubService.updateCoverImage(oclub);
            printMsg(resp, Result.success("保存成功"));
        } else {
            printMsg(resp, Result.dataError("oClubId错误"));
        }
    }

    @RequestMapping(value = "/notice.do", method = RequestMethod.GET)
    public String notice(HttpServletRequest request, HttpServletResponse resp) {
        long oClubId = WebUtils.paramOClubId(request);
        OClub club = oClubService.findValidClub(oClubId);
        if (club == null) {
            return redirect404(resp);
        }
        if (!isAdmin(request, resp)) {
            return null;
        }
        request.setAttribute("oClub", club);
        OClubNotice notice = oClubService.findClubNotice(oClubId);
        request.setAttribute("notice", notice);
        return getPcTemplPath("/club/notice");
    }

    /**
     * 保存公告
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/saveNotice.do", method = RequestMethod.POST)
    public void saveNotice(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long oClubId = WebUtils.paramOClubId(req);
        String content = WebUtils.param(req, "content", "");
        if (oClubId > 0) {
            OClub oclub = oClubService.findValidClub(oClubId);
            if (oclub == null) {
                printMsg(resp, Result.dataError("oClubId有误"));
                return;
            }
            if (!isAdmin(req, resp)) {
                return;
            }
            User user = userAuth.getUser(req, resp);
            OClubNotice notice = oClubService.findClubNotice(oClubId);
            notice.setContent(content);
            notice.setUpdateBy(user.getUid());
            int count = oClubService.updateClubNotice(notice);
            if (count > 0) {
                printMsg(resp, Result.success("保存成功"));
                //发审核
                if (StringUtils.isNotBlank(content)) {
                	censorOClubNoticeService.notifyCensorSystemCreate(req, notice);
                }
            } else {
                printMsg(resp, Result.error("保存失败"));
            }
        }
    }

    @RequestMapping(value = "/info.do", method = RequestMethod.GET)
    public String info(HttpServletRequest request, HttpServletResponse resp) {
        long oClubId = WebUtils.paramOClubId(request);
        OClub club = oClubService.findValidClub(oClubId);
        if (club == null) {
            return redirect404(resp);
        }
        if (!isAdmin(request, resp)) {
            return null;
        }
        request.setAttribute("oClub", club);
        return getPcTemplPath("/club/info");
    }

    /**
     * 更新简介
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/saveIntroduce.do", method = RequestMethod.POST)
    public void saveIntroduce(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long oClubId = WebUtils.paramOClubId(req);
        String introduce = WebUtils.param(req, "introduce", "");
        if (oClubId > 0) {
            OClub oClub = oClubService.findValidClub(oClubId);
            if (oClub == null) {
                printMsg(resp, Result.dataError("该车友会不存在"));
                return;
            }
            if (!isAdmin(req, resp)) {
                return;
            }
            User user = userAuth.getUser(req, resp);
            oClub.setIntroduce(introduce);
            oClub.setUpdateBy(user.getUid());
            int count = oClubService.updateIntroduce(oClub);
            if (count > 0) {
                //修改简介发送审核
                if (StringUtils.isNotBlank(introduce)) {
                    censorIntroduceService.notifyCensorSystemCreate(req, oClub);
                }
                printMsg(resp, Result.success("保存成功"));
            } else {
                printMsg(resp, Result.error("保存失败"));
            }
        } else {
            printMsg(resp, Result.dataError("该车友会不存在"));
        }
    }

    /**
     * 进入焦点图管理页面（登录管理员才可访问）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/focusImg.do", method = RequestMethod.GET)
    public String focusImg(HttpServletRequest request, HttpServletResponse resp) {
        long oClubId = WebUtils.paramOClubId(request);
        OClub club = oClubService.findValidClub(oClubId);
        if (club == null) {
            return redirect404(resp);
        }
        if (!isAdmin(request, resp)) {
            return null;
        }
        request.setAttribute("oClub", club);
        List<OClubFocusImg> imgList = oClubService.listFocusImg(oClubId);
        OClubFocusImg focusImg1;
        OClubFocusImg focusImg2;
        OClubFocusImg focusImg3;
        if (imgList != null && !imgList.isEmpty()) {
            focusImg1 = imgList.get(0);
            focusImg2 = imgList.get(1);
            focusImg3 = imgList.get(2);
        } else {
            focusImg1 = new OClubFocusImg();
            focusImg2 = new OClubFocusImg();
            focusImg3 = new OClubFocusImg();
        }
        request.setAttribute("focusImg1", focusImg1);
        request.setAttribute("focusImg2", focusImg2);
        request.setAttribute("focusImg3", focusImg3);
        request.setAttribute("defaultImg", defaultImg);
        return getPcTemplPath("/club/focusImg");
    }

    /**
     * 更新车友会焦点图
     *
     * @param request
     * @param model
     * @param resp
     * @
     */
    @RequestMapping(value = "/saveFocusImg.do", method = RequestMethod.POST)
    public void saveFocusImg(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long oClubId = WebUtils.paramOClubId(req);
        if (oClubId <= 0) {
            printMsg(resp, Result.dataError("该车友会不存在"));
            return;
        }
        if (!isAdmin(req, resp)) {
            return;
        }
        OClub club = oClubService.findValidClub(oClubId);
        if (club == null) {
            printMsg(resp, Result.dataError("该车友会不存在"));
            return;
        }
        String title1 = WebUtils.param(req, "title1", "");
        String imgUrl1 = removeDefault(WebUtils.param(req, "imgUrl1", ""));
        String url1 = WebUtils.param(req, "url1", "");
        String title2 = WebUtils.param(req, "title2", "");
        String imgUrl2 = removeDefault(WebUtils.param(req, "imgUrl2", ""));
        String url2 = WebUtils.param(req, "url2", "");
        String title3 = WebUtils.param(req, "title3", "");
        String imgUrl3 = removeDefault(WebUtils.param(req, "imgUrl3", ""));
        String url3 = WebUtils.param(req, "url3", "");
        int img1Seq = WebUtils.paramInt(req, "focusImg1Seq", 1);
        int img2Seq = WebUtils.paramInt(req, "focusImg2Seq", 2);
        int img3Seq = WebUtils.paramInt(req, "focusImg3Seq", 3);
        int TITLE_MAX_LENTH = 20;
        String TITLE_MAX_LENTH_TIP = "(20个文字以内)";

        if (StringUtils.isNotBlank(imgUrl1)) {
            if (imgUrl1.length() > OClubFocusImg.DB_MAX_LENGTH) {
                printMsg(resp, Result.error("第一张焦点图的图片地址过长"));
                return;
            } else if (StringUtils.isBlank(title1)) {
                printMsg(resp, Result.error("请输入第一张焦点图的标题"));
                return;
            } else if (title1.length() > TITLE_MAX_LENTH) {
                printMsg(resp, Result.error("第一张焦点图的标题过长" + TITLE_MAX_LENTH_TIP));
                return;
            }
            if (StringUtils.isBlank(url1)) {
                printMsg(resp, Result.error("请输入第一张焦点图的链接"));
                return;
            } else if (url1.matches(Regex.link.value) == false) {
                printMsg(resp, Result.error("第一张焦点图的链接不合法"));
                return;
            } else if (url1.length() > OClubFocusImg.DB_MAX_LENGTH) {
                printMsg(resp, Result.error("第一张焦点图的链接过长"));
                return;
            }
        } else {
            img1Seq = OClubFocusImg.EMPTY_SEQ;
            if (StringUtils.isNotBlank(title1) || StringUtils.isNotBlank(url1)) {
                printMsg(resp, Result.error("第一张焦点图您还没有上传"));
                return;
            }
        }

        if (StringUtils.isNotBlank(imgUrl2)) {
            if (imgUrl2.length() > OClubFocusImg.DB_MAX_LENGTH) {
                printMsg(resp, Result.error("第二张焦点图的图片地址过长"));
                return;
            } else if (StringUtils.isBlank(title2)) {
                printMsg(resp, Result.error("请输入第二张焦点图的标题"));
                return;
            } else if (title2.length() > TITLE_MAX_LENTH) {
                printMsg(resp, Result.error("第二张焦点图的标题过长" + TITLE_MAX_LENTH_TIP));
                return;
            }
            if (StringUtils.isBlank(url2)) {
                printMsg(resp, Result.error("请输入第二张焦点图的链接"));
                return;
            } else if (url2.matches(Regex.link.value) == false) {
                printMsg(resp, Result.error("第二张焦点图的链接不合法"));
                return;
            } else if (url2.length() > OClubFocusImg.DB_MAX_LENGTH) {
                printMsg(resp, Result.error("第二张焦点图的链接过长"));
                return;
            }
        } else {
            img2Seq = OClubFocusImg.EMPTY_SEQ;
            if (StringUtils.isNotBlank(title2) || StringUtils.isNotBlank(url2)) {
                printMsg(resp, Result.error("第二张焦点图您还没有上传"));
                return;
            }
        }

        if (StringUtils.isNotBlank(imgUrl3)) {
            if (imgUrl3.length() > OClubFocusImg.DB_MAX_LENGTH) {
                printMsg(resp, Result.error("第三张焦点图的图片地址过长"));
                return;
            } else if (StringUtils.isBlank(title3)) {
                printMsg(resp, Result.error("请输入第三张焦点图的标题"));
                return;
            } else if (title3.length() > TITLE_MAX_LENTH) {
                printMsg(resp, Result.error("第三张焦点图的标题过长" + TITLE_MAX_LENTH_TIP));
                return;
            }
            if (StringUtils.isBlank(url3)) {
                printMsg(resp, Result.error("请输入第三张焦点图的链接"));
                return;
            } else if (url3.matches(Regex.link.value) == false) {
                printMsg(resp, Result.error("第三张焦点图的链接不合法"));
                return;
            } else if (url3.length() > OClubFocusImg.DB_MAX_LENGTH) {
                printMsg(resp, Result.error("第三张焦点图的链接过长"));
                return;
            }
        } else {
            img3Seq = OClubFocusImg.EMPTY_SEQ;
            if (StringUtils.isNotBlank(title3) || StringUtils.isNotBlank(url3)) {
                printMsg(resp, Result.error("第三张焦点图您还没有上传"));
                return;
            }
        }
        if (StringUtils.isBlank(imgUrl1) && StringUtils.isBlank(imgUrl2) && StringUtils.isBlank(imgUrl3)) {
            printMsg(resp, Result.error("请至少上传一张焦点图"));
            return;
        }
        List<OClubFocusImg> list = oClubService.listFocusImg(oClubId);
        OClubFocusImg oClubFocusImg1 = null;
        OClubFocusImg oClubFocusImg2 = null;
        OClubFocusImg oClubFocusImg3 = null;
        if (!list.isEmpty()) {
            oClubFocusImg1 = list.get(0);
            oClubFocusImg2 = list.get(1);
            oClubFocusImg3 = list.get(2);
        }
        oClubFocusImg1 = parseClubFocusImg(oClubFocusImg1, oClubId, imgUrl1, title1, url1, img1Seq, oClubId);
        oClubFocusImg2 = parseClubFocusImg(oClubFocusImg2, oClubId, imgUrl2, title2, url2, img2Seq, oClubId);
        oClubFocusImg3 = parseClubFocusImg(oClubFocusImg3, oClubId, imgUrl3, title3, url3, img3Seq, oClubId);
        if (list.isEmpty()) {
            list = new ArrayList<OClubFocusImg>();
            list.add(oClubFocusImg1);
            list.add(oClubFocusImg2);
            list.add(oClubFocusImg3);
        }
        int count = oClubService.saveFocusImg(list);
        if (count > 0) {
            printMsg(resp, Result.success("保存成功"));
        } else {
            printMsg(resp, Result.error("保存失败"));
        }
    }

    /**
     * 组装焦点图对象
     *
     * @param oClubFocusImg
     * @param oClubId
     * @param imgUrl
     * @param title
     * @param url
     * @param seq
     * @param userId
     * @return
     */
    private OClubFocusImg parseClubFocusImg(OClubFocusImg oClubFocusImg, long oClubId, String imgUrl, String title, String url, int seq, long userId) {
        if (oClubFocusImg == null) {
            oClubFocusImg = new OClubFocusImg();
            oClubFocusImg.setoClubId(oClubId);
        }
        oClubFocusImg.setImgUrl(imgUrl);
        oClubFocusImg.setSeq(seq);
        oClubFocusImg.setTitle(title);
        oClubFocusImg.setUrl(url);
        oClubFocusImg.setUpdateAt(new Date());
        oClubFocusImg.setUpdateBy(userId);
        return oClubFocusImg;
    }

    /**
     * 删除焦点图
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/deleteFocusImg.do", method = RequestMethod.POST)
    public void deleteFocusImg(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long oClubId = WebUtils.paramOClubId(req);
        if (oClubId <= 0) {
            printMsg(resp, Result.dataError("该车友会不存在"));
            return;
        }
        if (!isAdmin(req, resp)) {
            return;
        }
        OClub club = oClubService.findValidClub(oClubId);
        if (club == null) {
            printMsg(resp, Result.dataError("该车友会不存在"));
            return;
        }
        long focusId = WebUtils.paramLong(req, "imgId", 0);
        if (focusId < 1) {
            printMsg(resp, Result.dataError());
        }
        if (oClubService.deleteFocusImgById(focusId)) {
            printMsg(resp, Result.success("焦点图删除成功"));
        } else {
            printMsg(resp, Result.success("焦点图删除失败"));
        }
    }

    /**
     * 移除默认图片
     *
     * @param imgUrl
     * @return
     */
    private String removeDefault(String imgUrl) {
        if (imgUrl.equals(OClubFocusImg.DEF_IMG)) {
            imgUrl = "";
        }
        return imgUrl;
    }

    @RequestMapping(value = "/getMyJoinClubNum.do", method = RequestMethod.GET)
    public void getMyJoinClubNum(HttpServletRequest request, HttpServletResponse resp) {
        WebUtils.setEncoding(request, resp);
        String callback = WebUtils.param(request, "callback", "");
        User user = userAuth.getUser(request, resp);
        if (user == null || user.getUid() <= 0) {
            printMsg(resp, Result.noLogin());
            return;
        }
        int clubNum = oClubService.countClub4Join(user.getUid());
        printMsg(resp, Result.success(clubNum), callback);
    }
}
